package com.eastfair.auth.listener;

import com.alibaba.fastjson.JSONObject;
import com.eastfair.annotation.log.entity.OptLogDTO;
import com.eastfair.auth.dto.SystemLogDTO;
import com.eastfair.auth.enumeration.HttpMethod;
import com.eastfair.auth.service.SystemLogService;
import com.eastfair.cache.auth.SystemRedisSubCacheKeyBuilder;
import com.eastfair.cache.repository.CacheOps;
import com.eastfair.core.model.CacheKey;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.core.plumelog.CompressMessage;
import com.eastfair.core.plumelog.RunLogMessage;
import com.eastfair.plumelog.util.LZ4Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class RedisMessageListener implements MessageListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    protected CacheOps cacheOps;


    @Autowired
    SystemLogService systemLogService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            // 获取消息
            byte[] messageBody = message.getBody();
            // 使用值序列化器转换
            Object msg = null;

            msg = redisTemplate.getValueSerializer().deserialize(messageBody);

            if (msg == null) {
                return;
            }
            CompressMessage compressMessage = (CompressMessage) msg;
            if (isSaveAgain(compressMessage)) {
                return;
            }
            List<String> messageList = LZ4Util.decompressorMessage(compressMessage);
            log.info("messageList is {} ", JSONObject.toJSONString(messageList));
            // 获取监听的频道
            byte[] channelByte = message.getChannel();
            // 使用字符串序列化器转换
            List<OptLogDTO> optLogDTOList = new ArrayList<>();
            for (String messageStr : messageList) {
                OptLogDTO optLogDTO = JSONObject.parseObject(messageStr, OptLogDTO.class);
                optLogDTOList.add(optLogDTO);
            }
            //批量添加
            List<SystemLogDTO> systemLogDTOList = new ArrayList<>();
            for (OptLogDTO optLogDTO : optLogDTOList) {
                SystemLogDTO systemLogDTO = new SystemLogDTO();
                BeanUtils.copyProperties(optLogDTO, systemLogDTO);
                systemLogDTO.setConsumingTime(optLogDTO.getConsumingTime().intValue());
                systemLogDTO.setHttpMethod(HttpMethod.get(optLogDTO.getHttpMethod()));
                systemLogDTOList.add(systemLogDTO);
            }
            log.info("systemLogDTOList is {} ", JSONObject.toJSONString(systemLogDTOList));
            Long l = System.currentTimeMillis();
            systemLogService.batchSave(systemLogDTOList);
            String s = String.format("插入条数：%s , 耗时：%s", systemLogDTOList.size(), (System.currentTimeMillis() - l));
            System.out.println(s);
        } catch (Exception e) {
        }
    }

    /**
     * 是否已经添加
     *
     * @param compressMessage
     * @return
     */
    public Boolean isSaveAgain(CompressMessage compressMessage) {
//        String key = "plumelog:" + compressMessage.getId();
        SystemRedisSubCacheKeyBuilder systemRedisSubCacheKeyBuilder = new SystemRedisSubCacheKeyBuilder();
        CacheKey cacheKey = systemRedisSubCacheKeyBuilder.key(compressMessage.getId());
        Integer i = cacheOps.get(cacheKey);
        if (i == null) {
            cacheOps.set(cacheKey, 1);
            return false;
        }
        return true;
    }
}
